import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import '../widget/num_change_widget.dart';

import '../pojo/srtspan.dart';
import '../tools/srttools.dart';

// 播放页
class PlayerScreen extends StatefulWidget {
  const PlayerScreen({super.key, required this.srtPath, required this.mp4Path});

  final String srtPath;
  final String mp4Path;
  @override
  State<PlayerScreen> createState() => _PlayerScreenState();
}

class _PlayerScreenState extends State<PlayerScreen> {
  // 播放器
  late final player = Player();
  late final controller = VideoController(player);

  // 字幕列表
  List<SrtSpan>? srts;

  // 当前字幕
  String curSubTitle = "";
  // 当前字幕索引
  int curIndex = 0;

  // 跳转字幕模式 跳过空闲片段
  bool jumpMode = false;
  DateTime? jumpDateTime;

  // 单句循环模式
  bool repeatMode = false;
  // 单句循环
  int repeatIndex = 0;

  // 键盘监听
  FocusNode focusNode = FocusNode();

  String inputSubTitle = "";
  String inputLine = "";
  String inputWord = "";

  List<String> curSubTitleWords = <String>[];
  Map<int, bool> checkMap = {};
  List<String> curInputs = <String>[];

  // 最后位置
  Duration? lastPosition;

  int jumpAfterBlankSpanTime = 3000; // 无字幕后3秒，跳转
  int jumpCheckAfterSpanTime = 3000; // 跳转后3秒再次检测

  String lastSubTitle = "";
  DateTime blankDateTime = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 1. 播放器
          Expanded(
              child: Video(
            controller: controller,
          )),
          // 2. 字幕栏
          buildSubtitlePanel(),
          // 3. 工具栏
          buildToolbar(),
          buildToolbarDebug(),
          // 4. 输入栏
          buildInputPanel(),
        ],
      ),
    );
  }

  buildSubtitlePanel() {
    return Container(
      height: 80,
      child: Text(
        curSubTitle,
        style: TextStyle(
            color: Colors.white, fontSize: 20, decoration: TextDecoration.none),
      ),
      decoration: BoxDecoration(color: Colors.black),
      width: double.infinity,
    );
  }

  buildInputPanel() {
    return Container(
      height: 180,
      child: Column(
        children: [
          Container(
              decoration: BoxDecoration(color: Colors.amberAccent),
              width: double.infinity,
              alignment: Alignment.center,
              height: 60,
              child: buildShow()),
          // Container(
          //   decoration: BoxDecoration(color: Colors.deepPurpleAccent),
          //   width: double.infinity,
          //   alignment: Alignment.center,
          //   height: 60,
          //   child: Text(
          //     inputSubTitle,
          //     style:
          //         TextStyle(color: Colors.white, decoration: TextDecoration.none),
          //   ),
          // ),
          Container(
            decoration: BoxDecoration(color: Colors.lightBlueAccent),
            width: double.infinity,
            alignment: Alignment.center,
            height: 60,
            child: Text(
              inputLine,
              style: TextStyle(
                  color: Colors.white, decoration: TextDecoration.none),
            ),
          ),
          KeyboardListener(
            focusNode: focusNode,
            autofocus: true, // 要开启自动焦点
            onKeyEvent: (KeyEvent event) {
              // print(event.toStringShort());
              // print(event.toStringShort());
              // print(event.deviceType);
              // print(event.character);
              // print(event.runtimeType);
              if (event.runtimeType == KeyDownEvent) {
                print(event.character);
                print(event.logicalKey.keyLabel);
                print(event.physicalKey.debugName);
                // print(event.deviceType);

                if (event.logicalKey.keyLabel == "Enter" ||
                    event.physicalKey.debugName == "Space") {
                  setState(() {
                    inputLine = inputWord;
                    inputWord = "";
                    // checkInputSubTitle();
                  });
                } else if (event.logicalKey.keyLabel == "Backspace") {
                  if (inputWord.length > 0) {
                    setState(() {
                      print(inputWord);
                      if (inputWord.length == 1) {
                        inputWord = "";
                      } else {
                        inputWord =
                            inputWord.substring(0, inputWord.length - 2);
                      }
                      print(inputWord);
                    });
                  }
                } else if (event.character != null) {
                  setState(() {
                    inputWord += event.character!;
                  });
                }
              }
            },
            child: Container(
              decoration: BoxDecoration(color: Colors.green),
              width: double.infinity,
              alignment: Alignment.center,
              height: 60,
              child: Text(
                inputWord,
                style: TextStyle(
                    color: Colors.white, decoration: TextDecoration.none),
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildToolbarDebug()
  {
    return Container(
        height: 40,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
        children: [IconButton(
          onPressed: () {
            op("open_movie");
          },
          icon: Icon(Icons.file_open),
          color: Colors.grey,
        ),
          IconButton(
            onPressed: () {
              op("open_srt");
            },
            icon: Icon(Icons.file_open_outlined),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("play_or_pause");
            },
            icon: Icon(Icons.play_arrow),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("prev_srt");
            },
            icon: Icon(Icons.replay),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("next_srt");
            },
            icon: Icon(Icons.refresh),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("switch_repeat");
            },
            icon: Icon(Icons.repeat_one),
            color: repeatMode ? Colors.green : Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op(
                "switch_jump_mode",
              );
            },
            icon: Icon(Icons.redo),
            color: jumpMode ? Colors.green : Colors.grey,
          ),
          IconButton(onPressed: foo, icon: Icon(Icons.abc)),
          IconButton(onPressed: foo, icon: Icon(Icons.call_to_action)),
          IconButton(onPressed: foo, icon: Icon(Icons.chrome_reader_mode)),
          IconButton(onPressed: foo, icon: Icon(Icons.zoom_out_map)),
          IconButton(onPressed: foo, icon: Icon(Icons.zoom_in_map)),
          Text(
            "${curIndex}",
            style: TextStyle(
                color: Colors.green,
                fontSize: 25,
                decoration: TextDecoration.none),
          ),
          IconButton(
              onPressed: () {
                op("test1");
              },
              icon: Icon(Icons.terminal)),]));
  }
  buildToolbar() {
    return Container(
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(onPressed: (){}, child: Text("暂停")),
          SizedBox(width: 20,),
          Text("重复:"),
          Material(child: NumberInputWidget(onValueChanged: repeatChange,num: 3,)),
          Text("次"),
          SizedBox(width: 20,),
          Text("等待:"),
          Material(child: NumberInputWidget(onValueChanged: repeatChange,num: 3,)),
          Text("秒"),
          SizedBox(width: 20,),
          OutlinedButton(onPressed: (){}, child: Text("退出")),
        ],
      ),
    );

  }

  void repeatChange(int num)
  {
    print("数字改变:${num}");
  }

  buildShow() {
    List<TextSpan> spans = <TextSpan>[];
    for (int i = 0; i < curSubTitleWords.length; i++) {
      TextSpan ts;
      if (checkMap[i] == true) {
        ts = TextSpan(text: curSubTitleWords[i], style: textStyle1);
      } else {
        ts = TextSpan(text: curSubTitleWords[i], style: textStyle2);
      }
      TextSpan ts2 = TextSpan(text: " ", style: blankStyle);
      spans.add(ts);
      spans.add(ts2);
    }
    InlineSpan span = TextSpan(children: spans);
    return Text.rich(span);
  }

  final TextStyle textStyle1 = const TextStyle(
      // color: Colors.amberAccent,
      color: Colors.green,
      decoration: TextDecoration.none,
      decorationColor: Colors.blue);

  final TextStyle textStyle2 = const TextStyle(
    // color: Colors.black,
    color: Colors.amberAccent,
    decoration: TextDecoration.none,
  );

  final TextStyle blankStyle = const TextStyle(
      decoration: TextDecoration.none, decorationColor: Colors.blue);

  Future<void> openSrt()
  async {
    // OS Error: Operation not permitted, errno = 1
    File file = File(widget.srtPath);
    String content = await file.readAsString();
    print("读取到内容:" + content);
    srts = SrtTools.handleSrtContent(content);
  }

  @override
  void initState() {
    super.initState();
    // FocusScope.of(context).requestFocus(focusNode);
    // FocusScope.of(context).autofocus(focusNode);
    player.open(Media(widget.mp4Path));

    openSrt();

    player.stream.position.listen((Duration position) {
      if (lastPosition != null) {
        if ((lastPosition!.inMilliseconds - position.inMilliseconds).abs() <
            100) {
          return;
        }
      }
      lastPosition = position;
      // print("lastPosition=${lastPosition}");
      curSubTitle = findSubtitles(position.inMilliseconds);

      if (repeatMode) {
        // 超出范围，要跳转到开头
        if (position.inMilliseconds > srts![repeatIndex].endTime! + 500) {
          player.seek(Duration(milliseconds: srts![repeatIndex].startTime!));
        }
      } else if (jumpMode) {
        if (curSubTitle == "") {
          if (lastSubTitle != "") {
            blankDateTime = DateTime.now();
          }
          lastSubTitle = curSubTitle;

          if (DateTime.now().difference(blankDateTime).inMilliseconds >
              jumpAfterBlankSpanTime) {
            // 跳转之后的间隔
            int span = 0;
            if (jumpDateTime != null) {
              Duration d = DateTime.now().difference(jumpDateTime!);
              span = d.inMilliseconds;
              print("跳转之后的间隔:${d.inMilliseconds}ms");
            }

            if (jumpDateTime == null || span > jumpCheckAfterSpanTime) {
              // 跳转下一个
              print("curSubTitle:" + curSubTitle);
              nextSrt();
              jumpDateTime = DateTime.now();
              return;
            }
          }
        }
      }

      setState(() {
        // Update UI.
      });
    });
  }

  void foo() {}

  Future<void> op(String s) async {
    print("op");
    switch (s) {
      case "play_or_pause":
        player.playOrPause();
        break;
      case "open_movie":
        {
          FilePickerResult? result = await FilePicker.platform.pickFiles();
          if (result != null) {
            print(result.files.single.path!);
            player.open(Media(result.files.single.path!));
          } else {
            print("用户取消选择");
          }
        }
        break;
      case "open_srt":
        {
          FilePickerResult? result = await FilePicker.platform.pickFiles();

          if (result != null) {
            String filePath = result.files.single.path!;
            print("选中的文件:" + filePath);
            // 2. 读取srt文件内容
            File file = File(result.files.single.path!);
            String content = await file.readAsString();
            print("读取到内容:" + content);
            // 3. 解析srt
            srts = SrtTools.handleSrtContent(content);
            for (SrtSpan srt in srts!) {
              print(srt);
            }
          } else {
            print("用户取消了选择");
          }
        }
        break;
      case "prev_srt":
        {
          print("前一句");
          preSrt();
        }
        break;
      case "next_srt":
        nextSrt();
        break;
      case "switch_jump_mode":
        setState(() {
          jumpMode = !jumpMode;
        });

        break;
      case "switch_repeat":
        setState(() {
          repeatMode = !repeatMode;
          if (repeatMode) {
            repeatIndex = curIndex;
            initRepeat();
          }
        });
        break;
    }
  }

  Future<void> preSrt() async {
    if (srts == null) return;

    // 是否在当前句
    SrtSpan curSpan = srts![curIndex];
    if (lastPosition!.inMilliseconds > curSpan.endTime!) {
      await player.seek(Duration(milliseconds: curSpan.startTime!));
      return;
    }
    // 还在当前句，切换到前一句
    int tmpIndex = curIndex - 1;
    // curIndex = tmpIndex;
    if (repeatMode) {
      repeatIndex--;
      // initRepeat();
    }
    if (tmpIndex < 1) return;

    SrtSpan span = srts![tmpIndex];
    int startTime = span!.startTime!;
    await player.seek(Duration(milliseconds: startTime));
  }

  Future<void> nextSrt() async {
    print("nextStr()");
    int tmpIndex = curIndex + 1;
    // curIndex = tmpIndex;
    repeatIndex++;
    initRepeat();
    print("后一句${tmpIndex}");
    if (tmpIndex >= srts!.length) return;
    if (srts == null) return;
    SrtSpan span = srts![tmpIndex];
    int startTime = span!.startTime!;
    await player.seek(Duration(milliseconds: startTime));
  }

  void initRepeat() {
    String tmp1 = srts![repeatIndex].content!;
    tmp1 = tmp1.replaceAll(",", " ");
    tmp1 = tmp1.replaceAll(".", " ");
    tmp1 = tmp1.replaceAll("<i>", "");
    tmp1 = tmp1.replaceAll("</i>", "");
    tmp1 = tmp1.replaceAll("-", "");
    tmp1 = tmp1.replaceAll("\n", " ");
    tmp1 = tmp1.replaceAll("'", "");
    tmp1 = tmp1.replaceAll("?", " ");
    tmp1 = tmp1.trim();
    // List<String> list1 = tmp1.split(" ");
    curSubTitleWords = tmp1.split(" ");
    checkMap = {};
    print(curSubTitleWords);
  }


  String findSubtitles(int ms) {
    String result = "";

    if (srts == null) return "";
    for (int i = 0; i < srts!.length; i++) {
      SrtSpan ss = srts![i];
      if (ss.startTime! < ms) {
        if (ss.endTime! > ms) {
          curIndex = i;
          return ss.content!;
        }
      } else {
        break;
      }
    }
    return result;
  }

}
